<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加载中...</title>
    <style>
        /* [保留] 页面主体、侧边栏、表格等样式与之前完全相同 */
        body { margin: 0; font-family: sans-serif; background-color: #f8f9fa; color: #333; display: flex; height: 100vh; }
        #sidebar { width: 220px; background-color: #343a40; color: white; padding: 15px; flex-shrink: 0; }
        #sidebar h1 { font-size: 1.5em; margin: 0 0 20px 0; text-align: center; }
        #menu-list { list-style-type: none; padding: 0; margin: 0; }
        #menu-list li a { display: block; color: #adb5bd; text-decoration: none; padding: 12px 15px; border-radius: 5px; transition: background-color 0.2s, color 0.2s; }
        #menu-list li a:hover { background-color: #495057; color: white; }
        #menu-list li a.active { background-color: #007bff; color: white; }
        #main-content { flex-grow: 1; padding: 25px; overflow-y: auto; position: relative; } /* 添加position relative */
        #content-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #dee2e6; padding-bottom: 15px; margin-bottom: 20px; }
        #content-title { font-size: 1.8em; margin: 0; }
        #data-table { width: 100%; border-collapse: collapse; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        #data-table thead { background-color: #e9ecef; }
        #data-table th, #data-table td { border: 1px solid #dee2e6; padding: 12px 15px; text-align: left; }
        #data-table tbody tr:hover { background-color: #f1f3f5; }
        .btn { padding: 8px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; color: white; margin-left: 8px; transition: opacity 0.2s; }
        .btn:hover { opacity: 0.85; }
        .btn-add { background-color: #28a745; }
        .btn-edit { background-color: #007bff; }
        .btn-delete { background-color: #dc3545; }
        .btn-confirm { background-color: #17a2b8; }
        .btn-cancel { background-color: #6c757d; }

        /* [新增] 模态弹窗 (Modal) 样式 */
        .modal-backdrop {
            display: none; /* 默认隐藏 */
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 100;
            justify-content: center;
            align-items: center;
        }
        .modal-backdrop.show {
            display: flex; /* 显示时变为flex布局来居中 */
        }
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            width: 90%;
            max-width: 500px;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #dee2e6;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        .modal-header h3 { margin: 0; }
        .modal-body .form-group { margin-bottom: 15px; }
        .modal-body label { display: block; margin-bottom: 5px; font-weight: bold; }
        .modal-body input { width: calc(100% - 20px); padding: 8px 10px; border: 1px solid #ced4da; border-radius: 4px; }
        .modal-footer {
            border-top: 1px solid #dee2e6;
            padding-top: 15px;
            margin-top: 20px;
            text-align: right;
        }
    </style>
</head>
<body>

    <nav id="sidebar">
        <h1 id="site-title-header">系统</h1>
        <ul id="menu-list"></ul>
    </nav>

    <main id="main-content">
        <div id="content-header">
            <h2 id="content-title">内容标题</h2>
            <div id="action-buttons"></div>
        </div>
        <table id="data-table">
            <thead id="table-head"></thead>
            <tbody id="table-body"></tbody>
        </table>
    </main>

    <!-- [新增] 模态弹窗的HTML结构 -->
    <div id="operation-modal" class="modal-backdrop">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modal-title">操作窗口</h3>
            </div>
            <div id="modal-body" class="modal-body">
                <!-- 表单或确认信息将动态插入这里 -->
            </div>
            <div id="modal-footer" class="modal-footer">
                <!-- 操作按钮将动态插入这里 -->
            </div>
        </div>
    </div>

    <!-- 关键改动：先加载外部的数据配置文件 -->
    <script src="config.js"></script>

    <!-- 然后再执行使用这些数据的渲染脚本 -->
    <script>
        // 全局变量来保存当前解析的路由信息
        let currentRoute = { pageId: null, action: null, itemId: null };

        document.addEventListener('DOMContentLoaded', () => {
            if (typeof AppConfig === 'undefined') {
                alert('错误：配置文件 config.js 加载失败或不存在！');
                return;
            }
            init();
            window.addEventListener('hashchange', handleRouteChange);
        });

        function init() {
            document.title = AppConfig.siteTitle;
            document.getElementById('site-title-header').textContent = AppConfig.siteTitle;
            renderMenu();
            handleRouteChange(); // 首次加载时处理路由
        }

        // [核心改造] 路由处理函数
        function handleRouteChange() {
            const hash = window.location.hash.substring(1);
            if (!hash) {
                // 如果没有哈希，重定向到第一个菜单项
                const defaultPageId = AppConfig.menu[0]?.id;
                if (defaultPageId) {
                    window.location.replace(`#${defaultPageId}`);
                }
                return;
            }

            const parts = hash.split('/');
            currentRoute = {
                pageId: parts[0],
                action: parts[1] || null, // add, edit, delete
                itemId: parts[2] ? parseInt(parts[2]) : null
            };

            // 无论何种路由，都先渲染背景的列表页面
            renderListPage(currentRoute.pageId);

            // 根据路由中的action决定是否显示弹窗
            if (currentRoute.action) {
                handleAction(currentRoute.pageId, currentRoute.action, currentRoute.itemId);
            } else {
                hideModal(); // 如果URL中没有action，确保弹窗是关闭的
            }
        }

        // 渲染列表页的主体内容
        function renderListPage(pageId) {
            const pageData = AppConfig.data[pageId];
            if (!pageData) {
                document.getElementById('content-title').textContent = '页面未找到';
                document.getElementById('table-head').innerHTML = '';
                document.getElementById('table-body').innerHTML = '<tr><td colspan="99">无效的页面标识。</td></tr>';
                return;
            }

            document.getElementById('content-title').textContent = pageData.title;
            renderTable(pageId, pageData);
            updateActiveMenu(pageId);
            renderActionButtons(pageId);
        }

        // [改造] renderTable现在只负责渲染，按钮的onclick行为已改变
        function renderTable(pageId, pageData) {
            const tableHead = document.getElementById('table-head');
            const tableBody = document.getElementById('table-body');
            tableHead.innerHTML = ''; tableBody.innerHTML = '';

            const headerRow = document.createElement('tr');
            pageData.columns.forEach(col => { headerRow.innerHTML += `<th>${col.label}</th>`; });
            headerRow.innerHTML += '<th>操作</th>';
            tableHead.appendChild(headerRow);

            pageData.rows.forEach(rowData => {
                const row = document.createElement('tr');
                pageData.columns.forEach(col => { row.innerHTML += `<td>${rowData[col.key] || ''}</td>`; });
                // [关键改动] 按钮现在通过修改URL哈希来触发操作
                row.innerHTML += `
                    <td>
                        <button class="btn btn-edit" onclick="location.hash='#${pageId}/edit/${rowData.id}'">编辑</button>
                        <button class="btn btn-delete" onclick="location.hash='#${pageId}/delete/${rowData.id}'">删除</button>
                    </td>`;
                tableBody.appendChild(row);
            });
        }

        // [改造] 新增按钮也通过修改URL哈希来触发
        function renderActionButtons(pageId) {
            document.getElementById('action-buttons').innerHTML = `<button class="btn btn-add" onclick="location.hash='#${pageId}/add'">新增</button>`;
        }

        // 根据路由信息处理弹窗
        function handleAction(pageId, action, itemId) {
            const pageData = AppConfig.data[pageId];
            if (!pageData) return;

            switch (action) {
                case 'add':
                    showFormModal(pageId);
                    break;
                case 'edit':
                    const itemToEdit = pageData.rows.find(row => row.id === itemId);
                    if (itemToEdit) {
                        showFormModal(pageId, itemToEdit);
                    } else {
                        alert('错误：找不到要编辑的项目。');
                        hideModal();
                    }
                    break;
                case 'delete':
                    const itemToDelete = pageData.rows.find(row => row.id === itemId);
                     if (itemToDelete) {
                        showDeleteConfirmModal(pageId, itemToDelete);
                    } else {
                        alert('错误：找不到要删除的项目。');
                        hideModal();
                    }
                    break;
            }
        }

        // --- 模态弹窗相关函数 ---

        function showModal() { document.getElementById('operation-modal').classList.add('show'); }
        function hideModal() {
            document.getElementById('operation-modal').classList.remove('show');
            // 关闭弹窗时，将URL重置回列表页，避免刷新时弹窗重现
            if (currentRoute.pageId) {
                location.hash = `#${currentRoute.pageId}`;
            }
        }

        function showFormModal(pageId, itemData = null) {
            const pageConfig = AppConfig.data[pageId];
            const modalTitle = document.getElementById('modal-title');
            const modalBody = document.getElementById('modal-body');
            const modalFooter = document.getElementById('modal-footer');

            modalTitle.textContent = itemData ? `编辑: ${pageConfig.title}` : `新增: ${pageConfig.title}`;

            let formHtml = '<form id="modal-form">';
            pageConfig.columns.forEach(col => {
                const value = itemData ? itemData[col.key] : '';
                formHtml += `
                    <div class="form-group">
                        <label for="form-input-${col.key}">${col.label}</label>
                        <input type="text" id="form-input-${col.key}" name="${col.key}" value="${value}">
                    </div>`;
            });
            formHtml += '</form>';
            modalBody.innerHTML = formHtml;

            const saveAction = itemData
                ? `saveItem('${pageId}', ${itemData.id})`
                : `saveItem('${pageId}')`;
            modalFooter.innerHTML = `
                <button class="btn btn-confirm" onclick="${saveAction}">保存</button>
                <button class="btn btn-cancel" onclick="hideModal()">取消</button>`;

            showModal();
        }

        function showDeleteConfirmModal(pageId, itemData) {
            const modalTitle = document.getElementById('modal-title');
            const modalBody = document.getElementById('modal-body');
            const modalFooter = document.getElementById('modal-footer');

            modalTitle.textContent = '确认删除';
            // 从配置中取一个关键字段来显示，增强用户体验
            const displayName = itemData[AppConfig.data[pageId].columns[0].key];
            modalBody.innerHTML = `<p>您确定要删除 "${displayName}" 这条记录吗？此操作无法撤销。</p>`;

            modalFooter.innerHTML = `
                <button class="btn btn-delete" onclick="deleteItem('${pageId}', ${itemData.id})">确认删除</button>
                <button class="btn btn-cancel" onclick="hideModal()">取消</button>`;

            showModal();
        }

        // --- 数据操作函数 ---

        function saveItem(pageId, itemId = null) {
            const pageData = AppConfig.data[pageId];
            const form = document.getElementById('modal-form');
            const formData = new FormData(form);

            if (itemId) { // 编辑
                const itemToUpdate = pageData.rows.find(row => row.id === itemId);
                formData.forEach((value, key) => {
                    itemToUpdate[key] = value;
                });
            } else { // 新增
                const newItem = { id: Date.now() };
                formData.forEach((value, key) => {
                    newItem[key] = value;
                });
                pageData.rows.push(newItem);
            }
            hideModal();
            renderTable(pageId, pageData); // 直接重绘表格，因为URL可能没变，不会触发hashchange
        }

        function deleteItem(pageId, itemId) {
            const pageData = AppConfig.data[pageId];
            const itemIndex = pageData.rows.findIndex(row => row.id === itemId);
            if (itemIndex > -1) {
                pageData.rows.splice(itemIndex, 1);
            }
            hideModal();
            renderTable(pageId, pageData);
        }

        // 之前未包含的辅助函数
        function renderMenu() {
            const menuList = document.getElementById('menu-list');
            menuList.innerHTML = '';
            AppConfig.menu.forEach(item => {
                const listItem = document.createElement('li');
                listItem.innerHTML = `<a href="#${item.id}" id="menu-${item.id}">${item.name}</a>`;
                menuList.appendChild(listItem);
            });
        }
        function updateActiveMenu(activeId) {
            document.querySelectorAll('#menu-list a').forEach(link => link.classList.remove('active'));
            const activeLink = document.getElementById(`menu-${activeId}`);
            if (activeLink) activeLink.classList.add('active');
        }

    </script>
</body>
</html>